// PcxImage.cpp: implementation of the PcxImage class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "PcxImage.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

#ifndef _UNICODE

IMPLEMENT_DYNAMIC(PcxImage, Image)

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

PcxImage::PcxImage()
{
	construct(CString());
}

PcxImage::PcxImage(LPTSTR file)
	: Image(file)
{
	construct(CString(file));
}

PcxImage::PcxImage(CString& file)
	: Image(file)
{
	construct(file);
}

PcxImage::~PcxImage()
{
	if (m_hbmp != NULL)
		::DeleteObject(m_hbmp);
}

BOOL PcxImage::loadImage()
{
	if (m_readpcxfile == NULL)
		return FALSE;
	if (m_file.IsEmpty())
		return FALSE;
	if (m_hbmp != NULL)
	{
		::DeleteObject(m_hbmp);
		m_hbmp = NULL;
	}

	return (m_readpcxfile(m_file.GetBuffer(0), 24, 1, 
		(unsigned int*)&m_hbmp, (unsigned int*)&m_hpal, 
		(long)this, NULL, 0) == 1);
}

void PcxImage::paint(CDC* pDC, AWTCanvas* canvas)
{
	if (m_hbmp == NULL)
		return;
	HDC hMemDC;
	HPALETTE hpalOld = NULL;
	hMemDC = ::CreateCompatibleDC(pDC->m_hDC);
	if (m_hpal)
	{  
		hpalOld = ::SelectPalette(pDC->m_hDC, m_hpal,0);
		::RealizePalette(pDC->m_hDC);
	}

	BITMAP bm;
	::GetObject(m_hbmp, sizeof(BITMAP), (LPSTR)&bm);
	
  HBITMAP hbmpOld = (HBITMAP)::SelectObject(hMemDC, m_hbmp);
	BitBlt(pDC->m_hDC, 0, 0, bm.bmWidth, bm.bmHeight, hMemDC, 0, 0, SRCCOPY);
  ::SelectObject(hMemDC,hbmpOld);
	
	if(hpalOld)
	{
		SelectPalette(pDC->m_hDC, hpalOld, 0);
		RealizePalette(pDC->m_hDC);
	}
}

CSize PcxImage::getSize()
{
	if (m_hbmp == NULL)
		return CSize(0,0);
	CSize sz;
	BITMAP bm;
	::GetObject(m_hbmp, sizeof(BITMAP), (LPSTR)&bm);
	sz.cx = bm.bmWidth;
	sz.cy = bm.bmHeight;
	return sz;
}

#endif
